package com.chainshop.product.service.impl;

import cn.hutool.core.util.NumberUtil;
import com.chainshop.common.core.domain.entity.SysDictData;
import com.chainshop.common.core.domain.pojo.ItemInformation;
import com.chainshop.product.domain.ProductVariants;
import com.chainshop.product.domain.vo.AddProductVo;
import com.chainshop.product.domain.vo.AttributeVo;
import com.chainshop.product.mapper.ItemInformationMapper;
import com.chainshop.product.mapper.ProductCategoryMapper;
import com.chainshop.product.service.IItemInformationService;
import com.chainshop.system.service.impl.SysDictDataServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 商品信息Service业务层处理
 * 
 * @author chainshop
 * @date 2024-08-07
 */
@Service
public class ItemInformationServiceImpl implements IItemInformationService 
{
    @Autowired
    private SysDictDataServiceImpl sysDictDataService;
    @Autowired
    private ItemInformationMapper itemInformationMapper;
    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    /**
     * 查询商品信息
     * 
     * @param id 商品信息主键
     * @return 商品信息
     */
    @Override
    public AddProductVo selectItemInformationById(Long id)
    {
        ProductVariants productVariants = itemInformationMapper.selectProductVariantsById(id);
        ItemInformation itemInformation = itemInformationMapper.selectItemInformationById(productVariants.getProductId());
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("product_unit");
        sysDictData.setDictValue(productVariants.getUnit()+"");
        List<SysDictData> sysDictData1 = sysDictDataService.selectDictDataList(sysDictData);

        AddProductVo addProductVo = new AddProductVo();
        addProductVo.setUnitN(sysDictData1.get(0));
        if(itemInformation!=null){

            addProductVo.setId(itemInformation.getId());
            addProductVo.setProductName(itemInformation.getProductName());
            addProductVo.setManufacturer(itemInformation.getManufacturer());
            addProductVo.setCategoryId(itemInformation.getCategoryId());
        }
        if(productVariants!=null){
            addProductVo.setPrice(productVariants.getPrice());
            addProductVo.setPurchasePrice(productVariants.getPurchasePrice());
            addProductVo.setUnit(productVariants.getUnit());
            String[] split = productVariants.getGoodsAttribute().substring(1,productVariants.getGoodsAttribute().length()-1).split(",");
            String[][] attributes = new String[split.length][];
            if(split.length!=0){
                for (int i = 0; i < split.length; i++) {
                    AttributeVo attributeVo = new AttributeVo();
                   attributes[i] = split[i].split(":");
                }
            }
            addProductVo.setAttribute(attributes);
        }

        return addProductVo;
       // return itemInformationMapper.selectItemInformationById(id);
    }

    @Override
    public List<ItemInformation> selectItemInformationList(ItemInformation itemInformation) {
        return itemInformationMapper.selectItemInformationList(itemInformation);
    }

    /**
     * 查询商品信息列表
     *
     * @param itemInformation 商品信息
     * @return 商品信息
     */
    @Override
    public List<AddProductVo> selectItemInformationsList(AddProductVo ProductVo)
    {
        List<AddProductVo> addProductVos = itemInformationMapper.selectItemInformationsList(ProductVo);
        addProductVos.forEach(addProductVo -> {
          addProductVo.setCategoryName(productCategoryMapper.getProductCategoryName(addProductVo.getCategoryId()));
        });
        return addProductVos;
    }

    /**
     * 新增商品信息
     * 
     * @param itemInformation 商品信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertItemInformation(AddProductVo productVo)
    {
        ItemInformation itemInformation = new ItemInformation();
        //随机生成商品id
        Integer[] integers = NumberUtil.generateBySet(100000000, 999999999, 1);
        itemInformation.setId(Long.valueOf(integers[0]));
        itemInformation.setProductName(productVo.getProductName());
        itemInformation.setCategoryId(productVo.getCategoryId());
        itemInformation.setManufacturer(productVo.getManufacturer());
        ProductVariants productVariants = new ProductVariants();
        int i = 0;
        ItemInformation itemInformation1 = itemInformationMapper.selectByName(productVo.getProductName());

            if (Objects.isNull(itemInformation1) || !(itemInformation.getProductName().equals(itemInformation1.getProductName())
                    && itemInformation.getCategoryId() == itemInformation1.getCategoryId()
                    && itemInformation.getManufacturer().equals(itemInformation1.getManufacturer()))) {
                i = itemInformationMapper.insertItemInformation(itemInformation);
                productVariants.setProductId(Long.valueOf(integers[0]));
                productVariants.setPrice(productVo.getPrice());
                productVariants.setPurchasePrice(productVo.getPurchasePrice());
                productVariants.setUnit(productVo.getUnit());
                String[][] attributes = productVo.getAttribute();

                List<List<String>> combinations = combineAttributes(attributes);

                // 打印结果
                for (List<String> combination : combinations) {
                    productVariants.setGoodsAttribute(combination.toString().trim());
                    i+=itemInformationMapper.insertProductVariants(productVariants);
                }
            }


                // 遍历属性
//                if(attributes.length!=0) {
//                    for (int j = 0; j <= attributes.length - 1; j++) {
//                        for (int k = 0; k <= attributes[j].length - 1; k++) {
//                            if(k<attributes[j].length)
//                                attribute = attribute + attributes[j][k] + ":";
//                        }
//                        attribute = attribute.substring(0,attribute.length()-1);
//                        attribute += ",";
//                    }
//                }

             else {
                productVariants.setProductId(itemInformation1.getId());
                productVariants.setPrice(productVo.getPrice());
                productVariants.setPurchasePrice(productVo.getPurchasePrice());
                productVariants.setUnit(productVo.getUnit());
                String attribute = "";
                String[][] attributes = productVo.getAttribute();
                // 遍历属性
//                if(attributes.length!=0) {
//                    for (int j = 0; j <= attributes.length - 1; j++) {
//                        for (int k = 0; k <= attributes[j].length - 1; k++) {
//                            if(k<attributes[j].length)
//                                attribute = attribute + attributes[j][k] + ":";
//                        }
//                        attribute = attribute.substring(0,attribute.length()-1);
//                        attribute += ",";
//                    }
//                }
                List<List<String>> combinations = combineAttributes(attributes);

                // 打印结果
                for (List<String> combination : combinations) {
                    productVariants.setGoodsAttribute(combination.toString());
                    i+=itemInformationMapper.insertProductVariants(productVariants);
                }
            }




        return i;
    }

    /**
     * 修改商品信息
     * 
     * @param itemInformation 商品信息
     * @return 结果
     */
    @Override
    public int updateItemInformation(AddProductVo addProductVo)
    {
        Long[] ids = {addProductVo.getVariantId()};
        int i = deleteItemInformationByIds(ids);
        i += insertItemInformation(addProductVo);
        return i;
    }

    /**
     * 批量删除商品信息
     * 
     * @param ids 需要删除的商品信息主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteItemInformationByIds(Long[] ids)
    {
        System.out.println("hhhhhhhhh");
        for (Long id : ids) {
            System.out.println(id);
        }
        ProductVariants productVariants = itemInformationMapper.selectProductVariantsById(ids[0]);

        int i = itemInformationMapper.deleteProductVariantsByIds(ids);
        System.out.println(productVariants);
        List<ProductVariants> productVariants1 = itemInformationMapper.selectProductVariantById(productVariants.getProductId());
        if (productVariants1.isEmpty()){
            i += itemInformationMapper.deleteItemInformationById(productVariants.getProductId());
        }
        //i += itemInformationMapper.deleteItemInformationByIds(ids);
        return i;
        //return itemInformationMapper.deleteItemInformationByIds(ids);
    }

    /**
     * 删除商品信息信息
     * 
     * @param id 商品信息主键
     * @return 结果
     */
    @Override
    public int deleteItemInformationById(Long id)
    {
        return itemInformationMapper.deleteItemInformationById(id);
    }

    @Override
    public List<SysDictData> getProductUnit() {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("product_unit");
        List<SysDictData> sysDictData1 = sysDictDataService.selectDictDataList(sysDictData);
        return sysDictData1;
    }

    @Override
    public List<AttributeVo> getProductAttribute(Long id) {
        List<AttributeVo> attributeVos = itemInformationMapper.getProductAttribute(id);
        attributeVos.forEach(attributeVo -> {
            attributeVo.setChildren(itemInformationMapper.getProductAttributeChildren(attributeVo.getId()));
        });
        return attributeVos;
    }
    public static List<List<String>> combineAttributes(String[][] attributes) {
        Map<String, List<String>> attrMap = new HashMap<>();
        for (String[] attr : attributes) {
            attrMap.computeIfAbsent(attr[0], k -> new ArrayList<>()).add(attr[1]);
        }

        List<List<String>> combinations = new ArrayList<>();
        combine(0, new ArrayList<>(), new ArrayList<>(attrMap.entrySet()), combinations);

        return combinations;
    }

    private static void combine(int index, List<String> current, List<Map.Entry<String, List<String>>> entries, List<List<String>> result) {
        if (index == entries.size()) {
            result.add(new ArrayList<>(current));
            return;
        }

        Map.Entry<String, List<String>> entry = entries.get(index);
        for (String value : entry.getValue()) {
            current.add(entry.getKey().trim() + ":" + value.trim());
            combine(index + 1, current, entries, result);
            current.remove(current.size() - 1); // Backtrack
        }
    }
}
